/****************************************************************************

	COPYRIGHT(C) MAXSI SOFTWARE, JONAS 'SORTIE' TERMANSEN 2008, 2009, 2010

    This file is part of Maxsi Installer.

    Maxsi Installer is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Maxsi Installer is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Maxsi Installer.  If not, see <http://www.gnu.org/licenses/>.

	*/ #include "MaxsiInstallerContributors.h" /*

	If you modify this file, please enter your name below and provide contact
	information in MaxsiEngineContributors.h. For more information please see
	MaxsiEngineContributors.h.
	
	Contributors to this file:

	- Jonas 'Sortie' Termansen
	- [your name here]

	MaxsiInstaller.exe
	The main installing technology utilized in the powerful Maxsi Distribution
	platform.

	PageInitializing.cpp
	Prior to installing, we need to figure out a few things about the product.

****************************************************************************/

#include "MaxsiEngine.h"
#include "MaxsiDistributionLink.h"
#include "Main.h" 
#include "UI.h" 
#include "Thread.h"
#include "Data.h"

bool PageInitialize::SetProgress(int Progress)
{
	if (!Initialized) { return false; }
	if (!ProgressBar) { return false; }

	SendMessage(ProgressBar,PBM_SETPOS,(WPARAM)Progress,(LPARAM)0);

	return true;
}


bool PageInitialize::InitializeForm(ME_Window* Parent)
{
	NeedInput	=	false;

	if ( ProductName )
	{
		HeaderTextOverride = BuildString(3,"Initializing ",ProductName,"!");
	}
	else
	{
		HeaderTextOverride = BuildString(1,"Welcome to Maxsi Distribution's Installer.");
	}

	BaseClass::InitializeForm(Parent);

	delete[] HeaderTextOverride; HeaderTextOverride = 0;

	RECT ClientSpace;
	GetClientRect (WindowHWND, &ClientSpace);

	ProgressBar			= CreateProgressBarA(Parent->WindowHWND,0,0,0,0,0);
	StatusLabel			= CreateLabelW		(Parent->WindowHWND,0,0,0,0,0);
	SubStatusLabel		= CreateLabelW		(Parent->WindowHWND,0,0,0,0,0);

	cmdRetry			= CreateButtonA		(Parent->WindowHWND,"Install",0,0,0,0);
	
	ProductNameField	= CreateTextA		(Parent->WindowHWND,ProductName,0,0,0,0);
	MasterServerField	= CreateTextA		(Parent->WindowHWND,MasterServer,0,0,0,0);
	ProductNameLabel	= CreateLabelW		(Parent->WindowHWND,0,0,0,0,0);
	MasterServerLabel	= CreateLabelW		(Parent->WindowHWND,0,0,0,0,0);

	if ( ProductName && MasterServer )
	{
		Connect();
	}
	else
	{
		RequestParameters();
	}

	NewResolution((WORD)ClientSpace.right,(WORD)ClientSpace.bottom);

	return true;
}

bool PageInitialize::Connect()
{
	if ( NeedInput )
	{
		WORD ProductNameFieldLen			=	(WORD)SendMessageA(ProductNameField,EM_LINELENGTH,(WPARAM) 0,(LPARAM) 0);
		
		if ( ProductNameFieldLen == 0 ) { return false; }
		if ( ProductNameFieldLen < sizeof(WORD) ) { ProductNameFieldLen = sizeof(WORD); }
		
		ProductName							=	new char[ProductNameFieldLen+1];
		ProductName[ProductNameFieldLen]	=	0;
		*(WORD*)(ProductName)				=	ProductNameFieldLen;
		SendMessageA(ProductNameField,EM_GETLINE,(WPARAM)0,(LPARAM)ProductName);

		WORD MasterServerFieldLen			=	(WORD)SendMessageA(MasterServerField,EM_LINELENGTH,(WPARAM) 0,(LPARAM) 0);
		
		if ( MasterServerFieldLen == 0 ) { return false; }
		if ( MasterServerFieldLen < sizeof(WORD) ) { MasterServerFieldLen = sizeof(WORD); }
		
		MasterServer						=	new char[MasterServerFieldLen+1];
		MasterServer[MasterServerFieldLen]	=	0;
		*(WORD*)(MasterServer)				=	MasterServerFieldLen;
		SendMessageA(MasterServerField,EM_GETLINE,(WPARAM)0,(LPARAM)MasterServer);
	}

	NeedInput	=	false;

	SendMessage(StatusLabel,WM_SETTEXT,(WPARAM)"Connecting to Master Content Server...",0);
	SendMessage(SubStatusLabel,WM_SETTEXT,(WPARAM)"",0);
	
	ShowWindow(cmdRetry,SW_HIDE);
	ShowWindow(ProductNameField,SW_HIDE);
	ShowWindow(MasterServerField,SW_HIDE);
	ShowWindow(ProductNameLabel,SW_HIDE);
	ShowWindow(MasterServerLabel,SW_HIDE);
	ShowWindow(ProgressBar,SW_SHOW);
	ShowWindow(StatusLabel,SW_SHOW);
	ShowWindow(SubStatusLabel,SW_SHOW);

	// Spawn the initializer thread
	ME_CreateThread(ThreadInitialize,WindowHWND);

	return true;
}

bool PageInitialize::RequestParameters()
{
	NeedInput	=	true;

	SendMessage(StatusLabel,WM_SETTEXT,(WPARAM)"",0);
	SendMessage(SubStatusLabel,WM_SETTEXT,(WPARAM)"To install a product using Maxsi Distribution, please enter its name and the Master Content Server handling it.\n\nProduct Name:\n\n\nMaster Content Server URL:",0);

	SendMessage(ProductNameLabel,WM_SETTEXT,(WPARAM)"Product Name:",0);
	SendMessage(MasterServerLabel,WM_SETTEXT,(WPARAM)"Master Content Server:",0);

	ShowWindow(ProductNameField,SW_SHOW);
	ShowWindow(ProductNameField,SW_SHOW);
	ShowWindow(MasterServerField,SW_SHOW);
	ShowWindow(ProductNameLabel,SW_SHOW);	
	ShowWindow(MasterServerLabel,SW_SHOW);
	ShowWindow(ProgressBar,SW_HIDE);
	ShowWindow(StatusLabel,SW_HIDE);
	ShowWindow(SubStatusLabel,SW_HIDE);

	return true;
}

bool PageInitialize::RenderForm(HWND hWnd)
{
	return	BaseClass::RenderForm(hWnd);
}

LRESULT PageInitialize::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	if (!Initialized) { return 0; }

	if ( message == WM_COMMAND )
	{
        switch(LOWORD(wParam)) 
        {
            case BN_CLICKED:			
			{
				HWND ClickedButton = (HWND)lParam;
				if ( ClickedButton == cmdRetry )
				{
					Connect();
				}
				break;
			}
			case MSG_SetStatus:
				SendMessage(StatusLabel,WM_SETTEXT,(WPARAM)lParam,0);
			break;		
			case MSG_SetProgress:
				SetProgress((int)lParam);
			break;
			case GotoFailurePage:
				SendMessage(StatusLabel,WM_SETTEXT,(WPARAM)"Couldn't connect to the Master Content Server!",0);
				SendMessage(SubStatusLabel,WM_SETTEXT,(WPARAM)"Maxsi Distribution requires an Internet Connection. Please make sure that Maxsi Distribution may access the Internet and that no firewalls are preventing Maxsi Distribution from accessing the Internet.\n\nIf you are positive that your Internet is working correctly and nothing is preventing Maxsi Distribution from connecting to the Master Content Server, then please contact Maxsi Software.\n\nPlease attempt to re-connect by pressing Install.",0);

				ShowWindow(cmdRetry,SW_SHOW);
				break;
			case GotoSuccessPage:
				if ( IsUpdate )
				{
					ReplaceSelfWith( (MaxsiUI_Form*) new PageInstaller );
				}
				else
				{
					ReplaceSelfWith( (MaxsiUI_Form*) new PageWelcome );
				}
				break;
			case QuitMessage:
				PostQuitMessage(0);
		}
	}
	else
	{
		return BaseClass::WindowProc(hWnd,message,wParam,lParam);
	}
    return (0);

}


bool PageInitialize::TerminateForm()
{
	// Avoid calling this function twice, or worse,
	// if one of the functions called here invokes another
	// windows message that eventually leads to this point of code again.
	if (!Initialized) { return false; }
	Initialized	=	false;

	DestroyWindow(ProgressBar);
	DestroyWindow(StatusLabel);
	DestroyWindow(SubStatusLabel);
	DestroyWindow(cmdRetry);
	DestroyWindow(ProductNameField);
	DestroyWindow(MasterServerField);
	DestroyWindow(ProductNameLabel);
	DestroyWindow(MasterServerLabel);

	delete[]	HeaderTextOverride;

	// If we are here, we are safe. Call the parent and ask him to continue our work.
	// Make sure he sets Initialized to false afterwards.
	Initialized	=	true;
	BaseClass::TerminateForm();
	return true;
}

bool PageInitialize::NewResolution( WORD Width, WORD Height)
{
	MoveWindow(ProgressBar,25,85,Width-25-25,18,TRUE);
	MoveWindow(StatusLabel,25,55,Width-25-25,85-55,TRUE);
	MoveWindow(SubStatusLabel,25,110,Width-25-25,Height-110-3*24,TRUE);
	MoveWindow(cmdRetry	,Width-1*125,Height-2*24,100,24,TRUE);
	MoveWindow(ProductNameLabel,25,55,Width-25-25,24,TRUE);
	MoveWindow(ProductNameField,25,79,Width-25-25,24,TRUE);
	MoveWindow(MasterServerLabel,25,127,Width-25-25,24,TRUE);
	MoveWindow(MasterServerField,25,151,Width-25-25,24,TRUE);

	BaseClass::NewResolution(Width,Height);

	return true;
}